package com.hyz.reggie.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hyz.reggie.common.BaseContext;
import com.hyz.reggie.dao.CartDao;
import com.hyz.reggie.pojo.R;
import com.hyz.reggie.pojo.ShoppingCart;
import com.hyz.reggie.service.CartService;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CartServiceImpl extends ServiceImpl<CartDao, ShoppingCart> implements CartService {
    @Override
    public ShoppingCart add(ShoppingCart shoppingCart) {
        Long userId = BaseContext.getCurrentID();
        shoppingCart.setUserId(userId);
        LambdaQueryWrapper<ShoppingCart> qwq = new LambdaQueryWrapper<>();
        if (shoppingCart.getSetmealId() != null) {
            qwq.eq(ShoppingCart::getSetmealId, shoppingCart.getSetmealId());
        }
        if (shoppingCart.getDishId() != null) {
            qwq.eq(ShoppingCart::getDishId, shoppingCart.getDishId());
        }
        qwq.eq(ShoppingCart::getUserId, userId);
        ShoppingCart cart = getOne(qwq);
        if (cart != null) {
            cart.setNumber(cart.getNumber() + 1);
            updateById(cart);
            return cart;
        }
        shoppingCart.setNumber(1);
        save(shoppingCart);
        return shoppingCart;
    }

    @Override
    public List<ShoppingCart> getList() {
        Long userId = BaseContext.getCurrentID();
        LambdaQueryWrapper<ShoppingCart> qwq = new LambdaQueryWrapper<>();
        qwq.eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> list = list(qwq);
        return list;
    }

    @Override
    public R sub(ShoppingCart shoppingCart) {
        Long userId = BaseContext.getCurrentID();
        LambdaQueryWrapper<ShoppingCart> qwq = new LambdaQueryWrapper<>();
        qwq.eq(ShoppingCart::getUserId, userId);
        if (shoppingCart.getDishId() != null) {
            qwq.eq(ShoppingCart::getDishId, shoppingCart.getDishId());
        }
        if (shoppingCart.getSetmealId() != null) {
            qwq.eq(ShoppingCart::getSetmealId, shoppingCart.getSetmealId());
        }
        ShoppingCart one = getOne(qwq);
        if (one.getNumber() == 1) {
            remove(qwq);
            return R.success("删除成功~");
        }
        one.setNumber(one.getNumber()-1);
        updateById(one);
        return R.success(one);
    }

    @Override
    public void clean() {
        Long userId = BaseContext.getCurrentID();
        LambdaQueryWrapper<ShoppingCart> qwq = new LambdaQueryWrapper<>();
        qwq.eq(ShoppingCart::getUserId, userId);
        remove(qwq);
    }
}
